package ciicos.equ.service.impl;

import ciicos.base.model.filter.RuleInfo;
import ciicos.equ.entity.EquBaseEntity;
import ciicos.equ.entity.EquPointEntity;
import ciicos.equ.mapper.EquBaseMapper;
import ciicos.equ.model.equbase.EquBaseForm;
import ciicos.equ.model.equbase.EquBasePagination;
import ciicos.equ.service.EquBaseService;
import ciicos.equ.service.EquPointService;
import ciicos.model.visiual.superQuery.ConditionJsonModel;
import ciicos.model.visiual.superQuery.SuperQueryConditionModel;
import ciicos.model.visiual.superQuery.SuperQueryJsonModel;
import ciicos.permission.model.authorize.AuthorizeConditionModel;
import ciicos.permission.service.AuthorizeService;
import ciicos.permission.util.GenUtil;
import ciicos.util.*;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 设备信息
 * 版本： V3.2.0
 * 版权：
 * 作者： 企业研发中心
 * 日期： 2024-02-06
 */
@Service
public class EquBaseServiceImpl extends ServiceImpl<EquBaseMapper, EquBaseEntity> implements EquBaseService {


    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private AuthorizeService authorizeService;


    @Autowired
    private EquPointService equPointService;


    @Override
    public List<EquBaseEntity> getList(EquBasePagination equBasePagination) {
        return getTypeList(equBasePagination, equBasePagination.getDataType());
    }

    @Override
    public List<EquBaseEntity> getTypeList(EquBasePagination equBasePagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList<>();
        int total = 0;
        int equBaseNum = 0;
        QueryWrapper<EquBaseEntity> equBaseQueryWrapper = new QueryWrapper<>();
        int equPointNum = 0;
        QueryWrapper<EquPointEntity> equPointQueryWrapper = new QueryWrapper<>();

//树形，异步父级查询条件
        long equPointcount = equPointService.count();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(equBasePagination.getSuperQueryJson())) {
            SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(equBasePagination.getSuperQueryJson(), SuperQueryJsonModel.class);
            String matchLogic = superQueryJsonModel.getMatchLogic();
            List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
            for (ConditionJsonModel conditionjson : superQueryList) {
                Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
                Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
                String tableName = configMap.get("relationTable") != null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
                if (map.get("multiple") != null) {
                    if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
                        conditionjson.setFieldValue("[]");
                    }
                }
                conditionjson.setTableName(tableName);
            }
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList = new ArrayList<>();


            int equBaseNum1 = 0;
            QueryWrapper<EquBaseEntity> equBaseSuperWrapper = new QueryWrapper<>();
            equBaseNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(equBaseSuperWrapper, superQueryList, matchLogic, "equ_base")
                    , new EquBaseEntity(), equBaseNum1);
            if (equBaseNum1 > 0) {
                List<String> equBaseList = this.list(equBaseSuperWrapper).stream().map(EquBaseEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(equBaseList);
                intersectionSuperList.add(equBaseList);
            }
            int equPointNum1 = 0;
            QueryWrapper<EquPointEntity> equPointSuperWrapper = new QueryWrapper<>();
            equPointNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(equPointSuperWrapper, superQueryList, matchLogic, "equ_point")
                    , new EquPointEntity(), equPointNum1);
            if (equPointNum1 > 0 && equPointcount > 0) {

                List<String> equPointList = equPointService.list(equPointSuperWrapper).stream().map(EquPointEntity::getEquid).collect(Collectors.toList());
                allSuperList.addAll(equPointList);
                intersectionSuperList.add(equPointList);
            }
            superOp = matchLogic;
            //and or
            if (matchLogic.equalsIgnoreCase("and")) {
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }
        boolean pcPermission = false;
        boolean appPermission = false;
        boolean isPc = ServletUtil.getHeader("ciicos-origin").equals("pc");
        if (isPc && pcPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object equBaseObj = authorizeService.getCondition(new AuthorizeConditionModel(equBaseQueryWrapper, equBasePagination.getMenuId(), "equ_base"));
                if (ObjectUtil.isEmpty(equBaseObj)) {
                    return new ArrayList<>();
                } else {
                    equBaseQueryWrapper = (QueryWrapper<EquBaseEntity>) equBaseObj;
                    if (equBaseQueryWrapper.getExpression().getNormal().size() > 0) {
                        equBaseNum++;
                    }
                }
                Object equPointObj = authorizeService.getCondition(new AuthorizeConditionModel(equPointQueryWrapper, equBasePagination.getMenuId(), "equ_point"));
                if (ObjectUtil.isEmpty(equPointObj)) {
                    return new ArrayList<>();
                } else {
                    equPointQueryWrapper = (QueryWrapper<EquPointEntity>) equPointObj;
                    if (equPointQueryWrapper.getExpression().getNormal().size() > 0) {
                        equPointNum++;
                    }
                }
            }
        }
        if (!isPc && appPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object equBaseObj = authorizeService.getCondition(new AuthorizeConditionModel(equBaseQueryWrapper, equBasePagination.getMenuId(), "equ_base"));
                if (ObjectUtil.isEmpty(equBaseObj)) {
                    return new ArrayList<>();
                } else {
                    equBaseQueryWrapper = (QueryWrapper<EquBaseEntity>) equBaseObj;
                    if (equBaseQueryWrapper.getExpression().getNormal().size() > 0) {
                        equBaseNum++;
                    }
                }


                Object equPointObj = authorizeService.getCondition(new AuthorizeConditionModel(equPointQueryWrapper, equBasePagination.getMenuId(), "equ_point"));
                if (ObjectUtil.isEmpty(equPointObj)) {
                    return new ArrayList<>();
                } else {
                    equPointQueryWrapper = (QueryWrapper<EquPointEntity>) equPointObj;
                    if (equPointQueryWrapper.getExpression().getNormal().size() > 0) {
                        equPointNum++;
                    }
                }


            }
        }

        if (ObjectUtil.isNotEmpty(equBasePagination.getType())) {
            equBaseNum++;
            equBaseQueryWrapper.lambda().in(EquBaseEntity::getType, equBasePagination.getType());

        }

        if (ObjectUtil.isNotEmpty(equBasePagination.getName())) {
            equBaseNum++;

            equBaseQueryWrapper.lambda().like(EquBaseEntity::getName, equBasePagination.getName());

        }

        if (ObjectUtil.isNotEmpty(equBasePagination.getCode())) {
            equBaseNum++;

            equBaseQueryWrapper.lambda().like(EquBaseEntity::getCode, equBasePagination.getCode());

        }

        if (ObjectUtil.isNotEmpty(equBasePagination.getPacket())) {
            equBaseNum++;

            equBaseQueryWrapper.lambda().like(EquBaseEntity::getPacket, equBasePagination.getPacket());

        }

        if (equPointNum > 0) {
            List<String> equPointIdList = equPointService.list(equPointQueryWrapper).stream().filter(t -> StringUtil.isNotEmpty(t.getEquid())).map(t -> t.getEquid()).collect(Collectors.toList());
            long count = equPointService.count();
            if (count > 0) {
                intersectionList.add(equPointIdList);
            }
            AllIdList.addAll(equPointIdList);
        }
        total += equPointNum;
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }
            equBaseQueryWrapper.lambda().in(EquBaseEntity::getId, intersection);
        }
        //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            equBaseQueryWrapper.lambda().and(t -> t.in(EquBaseEntity::getId, finalAllSuperIDlist));
        }


        //排序
        if (StringUtil.isEmpty(equBasePagination.getSidx())) {
            equBaseQueryWrapper.lambda().orderByDesc(EquBaseEntity::getCreatortime);
        } else {
            try {
                String sidx = equBasePagination.getSidx();
                EquBaseEntity equBaseEntity = new EquBaseEntity();
                Field declaredField = equBaseEntity.getClass().getDeclaredField(sidx);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                equBaseQueryWrapper = "asc".equals(equBasePagination.getSort().toLowerCase()) ? equBaseQueryWrapper.orderByAsc(value) : equBaseQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        // 过滤条件

        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<EquBaseEntity> page = new Page<>(equBasePagination.getCurrentPage(), equBasePagination.getPageSize());
                IPage<EquBaseEntity> userIPage = this.page(page, equBaseQueryWrapper);
                return equBasePagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<EquBaseEntity> list = new ArrayList();
                return equBasePagination.setData(list, list.size());
            }
        } else {
            return this.list(equBaseQueryWrapper);
        }
    }

    public QueryWrapper wrapperHandle(QueryWrapper<?> wrapper, String id, Class<?> aClass, String type, String tableName) {
        try {
            // 避免空and
            wrapper.apply(" 1=1 ");
            List<RuleInfo> ruleInfos = generaterSwapUtil.getFilterCondition(id);
            for (RuleInfo info : ruleInfos) {
                String field = info.getField();
                if ("main".equals(type) && field.contains("-")) {
                    continue;
                }
                if ("main".equals(type) && field.contains("_jnpf_")) {
                    continue;
                }
                if ("sub".equals(type) && !field.contains("-")) {
                    continue;
                }
                if ("sub-jnpf".equals(type) && !field.contains("_jnpf_")) {
                    continue;
                }
                String fieldName = field;
                String table = "";
                if (field.contains("-")) {
                    fieldName = field.split("-")[1];
                }
                if (field.contains("_jnpf_")) {
                    fieldName = field.split("_jnpf_")[1];
                    table = field.split("_jnpf_")[0];
                    table = table.replace("jnpf_", "");
                }
                if ("sub-jnpf".equals(type) && !tableName.equals(table)) {
                    continue;
                }
                Field declaredField = aClass.getDeclaredField(fieldName);
                declaredField.setAccessible(true);
                String fieldDb = declaredField.getAnnotation(TableField.class).value();
                GenUtil genUtil = JsonUtil.getJsonToBean(info, GenUtil.class);
                genUtil.solveValue(wrapper, fieldDb);
            }
            return wrapper;
        } catch (Exception e) {
            return wrapper;
        }
    }

    @Override
    public EquBaseEntity getInfo(String id) {
        QueryWrapper<EquBaseEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EquBaseEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(EquBaseEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, EquBaseEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(EquBaseEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }

    //子表方法
    @Override
    public List<EquPointEntity> getEquPointList(String id, EquBasePagination equBasePagination) {
        QueryWrapper<EquPointEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper = equPointService.getChild(equBasePagination, queryWrapper);
        queryWrapper.lambda().eq(EquPointEntity::getEquid, id);
        this.wrapperHandle(queryWrapper, equBasePagination.getModuleId(), EquPointEntity.class, "sub", "equPoint");
        return equPointService.list(queryWrapper);
    }

    @Override
    public List<EquPointEntity> getEquPointList(String id) {
        QueryWrapper<EquPointEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EquPointEntity::getEquid, id);
        return equPointService.list(queryWrapper);
    }

    //列表子表数据方法


    //验证表单唯一字段
    @Override
    public String checkForm(EquBaseForm form, int i) {
        int total = 0;
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        String countRecover = "";
        if (isUp) {
            id = form.getId();
        }
        if (ObjectUtil.isNotEmpty(form.getCode())) {
            QueryWrapper<EquBaseEntity> codeWrapper = new QueryWrapper<>();
            codeWrapper.lambda().eq(EquBaseEntity::getCode, form.getCode());
            if (isUp) {
                codeWrapper.lambda().ne(EquBaseEntity::getId, id);
            }
            if ((int) this.count(codeWrapper) > 0) {
                total++;
                countRecover = "编号";
            }
        }
        if (ObjectUtil.isNotEmpty(form.getName())) {
            QueryWrapper<EquBaseEntity> codeWrapper = new QueryWrapper<>();
            codeWrapper.lambda().eq(EquBaseEntity::getName, form.getName());
            if (isUp) {
                codeWrapper.lambda().ne(EquBaseEntity::getId, id);
            }
            if ((int) this.count(codeWrapper) > 0) {
                total++;
                countRecover = "名称";
            }
        }
        return countRecover;
    }


}
